<template>
    <div class="inbound-management-container">
        <el-card shadow="never">
            <!-- 头部区域 -->
            <template #header>
                <div class="card-header">
                    <span class="header-title">入库单管理</span>
                </div>
            </template>

            <!-- 搜索和操作区域 -->
            <div class="search-operation-area">
                <!-- 搜索表单 -->
                <el-form :model="formData" ref="formRef" label-width="90px" :inline="true" class="search-form">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="入库编号" prop="inboundCode">
                                <el-input v-model="formData.inboundCode" placeholder="请输入入库编号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="入库名称" prop="inboundName">
                                <el-input v-model="formData.inboundName" placeholder="请输入入库名称" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="计划编号" prop="planId">
                                <el-input v-model="formData.planId" placeholder="请输入计划编号" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="仓库" prop="warehouseId">
                                <el-select v-model="formData.warehouseId" placeholder="请选择仓库" clearable filterable
                                    style="width:100%">
                                    <el-option v-for="item in warehouseOptions" :key="item.warehouseId"
                                        :label="item.warehouseName" :value="item.warehouseId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="padding-left: 50px;">
                            <el-form-item>
                                <!-- 搜索和重置按钮 -->
                                <el-button type="primary" @click="handleSearch">搜索</el-button>
                                <el-button type="info" :plain="true" @click="resetForm">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 操作按钮区域 -->
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-button @click="toInsert" type="primary" :plain="true">+添加</el-button>
                        <el-button type="success" :plain="true" :disabled="selectedRows.length !== 1"
                            @click="handleUpdate(selectedRows[0])">修改</el-button>
                        <el-button type="danger" :plain="true" :disabled="!selectedRows.length"
                            @click="handleBatchDelete">删除</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 数据表格 -->
            <el-table :data="page.records" style="width: 100%" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="入库单编号" prop="inboundCode" width="150" fixed>
                    <template #default="{ row }">
                        <el-link type="primary" @click.stop="openDetailDialog(row)">
                            {{ row.inboundCode }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column label="入库单名称" prop="inboundName" width="150" />
                <el-table-column label="生产计划编号" prop="planId" width="150" />
                <el-table-column label="仓库" prop="warehouseName" width="120" />
                <el-table-column label="计划入库总数量" prop="totalQuantity" width="120" />
                <el-table-column label="实际入库总数量" prop="actualQuantity" width="120" />
                <el-table-column label="入库日期" prop="createTime" width="120">
                    <template #default="{ row }">
                        {{ formatDate(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="inboundStatus" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.inboundStatus)">
                            {{ getStatusText(row.inboundStatus) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="操作" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button type="success" size="small" @click.stop="handleExecute(row)"
                            :disabled="row.inboundStatus === 1">
                            {{ row.inboundStatus === 1 ? '已入库' : '执行入库' }}
                        </el-button>
                        <el-button type="primary" size="small" @click.stop="handleUpdate(row)"
                            :disabled="row.inboundStatus === 1">
                            修改
                        </el-button>
                        <el-button type="danger" size="small" @click.stop="handleDelete(row)"
                            :disabled="row.inboundStatus === 1">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size"
                :page-sizes="[5, 10, 20, 50]" :total="page.total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" background>
            </el-pagination>

            <!-- 表单弹窗 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" :destroy-on-close="true"
                @closed="handleDialogClosed">
                <router-view @ref-table="refTable" :data="currentRow"></router-view>
            </el-dialog>

            <!-- 执行入库弹窗 -->
            <el-dialog title="执行入库" v-model="executeDialogVisible" width="500px" :destroy-on-close="true">
                <el-form :model="executeForm" ref="executeFormRef" label-width="100px">
                    <el-form-item label="入库单编号">
                        <el-input v-model="executeForm.inboundCode" disabled />
                    </el-form-item>
                    <el-form-item label="入库单名称">
                        <el-input v-model="executeForm.inboundName" disabled />
                    </el-form-item>
                    <el-form-item label="仓库">
                        <el-input v-model="executeForm.warehouseName" disabled />
                    </el-form-item>
                    <el-form-item label="计划数量">
                        <el-input v-model="executeForm.totalQuantity" disabled />
                    </el-form-item>
                    <el-form-item label="实际数量" prop="actualQuantity"
                        :rules="[{ required: true, message: '请输入实际数量' }, { validator: validateQuantity }]">
                        <el-input-number v-model="executeForm.actualQuantity" :min="1" :max="executeForm.totalQuantity"
                            style="width: 100%" />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <el-button @click="executeDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmExecute" :loading="executing">
                        {{ executing ? '入库中...' : '确认入库' }}
                    </el-button>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import request from '@/api/request'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 搜索表单数据
const formData = ref({
    inboundCode: '',
    inboundName: '',
    planId: '',
    warehouseId: ''
})

// 仓库选项
const warehouseOptions = ref([])

// 分页数据
const page = ref({
    current: 1,
    size: 5,
    total: 0,
    records: []
})

// 选中行数据
const selectedRows = ref([])
const currentRow = ref(null)

// 弹窗控制
const dialogVisible = ref(false)
const executeDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const executeFormRef = ref(null)

// 执行入库表单
const executeForm = reactive({
    inboundId: '',
    inboundCode: '',
    inboundName: '',
    warehouseName: '',
    totalQuantity: 0,
    actualQuantity: 0,
})

// 执行状态
const executing = ref(false)

// 加载仓库列表
const loadWarehouseList = () => {
    return request({
        url: '/warehouse/tree',
        method: 'get'
    }).then(res => {
        warehouseOptions.value = res.data || []
    })
}

// 加载数据
const loadData = async () => {
    try {
        const params = {
            current: page.value.current,
            size: page.value.size,
            ...formData.value
        }

        // 移除空值参数
        Object.keys(params).forEach(key => {
            if (params[key] === '' || params[key] == null) {
                delete params[key]
            }
        })

        const res = await request({
            url: '/inboundOrder/page',
            method: 'get',
            params
        })

        if (res.data && res.data.records) {
            // 确保仓库列表已加载
            if (warehouseOptions.value.length === 0) {
                await loadWarehouseList()
            }

            // 创建仓库ID到名称的映射
            const warehouseMap = {}
            warehouseOptions.value.forEach(item => {
                warehouseMap[item.warehouseId] = item.warehouseName
            })

            // 为入库单数据添加仓库名称
            res.data.records.forEach(record => {
                record.warehouseName = warehouseMap[record.warehouseId] || '未知仓库'
            })

            page.value = res.data
            console.log('加载数据成功:', page.value)
        }
    } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
    }
}

// 执行入库
const handleExecute = (row) => {
    if (row.inboundStatus === 1) {
        ElMessage.warning('该入库单已完成入库')
        return
    }

    // 填充执行表单数据
    Object.assign(executeForm, {
        inboundId: row.inboundId,
        inboundCode: row.inboundCode,
        inboundName: row.inboundName,
        planId:row.planId,
        warehouseId: row.warehouseId,
        warehouseName: row.warehouseName,
        materialId: row.productId,
        operatorId: row.operatorId,
        batchNo: row.batchNo,
        totalQuantity: row.totalQuantity,
        actualQuantity: row.totalQuantity, // 默认等于计划数量
    })

    executeDialogVisible.value = true
}

// 确认执行入库
const confirmExecute = async () => {
    try {
        // 表单验证
        await executeFormRef.value.validate()

        executing.value = true
        
        // 正确的参数结构 - 使用实际输入的数量
        let data = {
            inboundId: executeForm.inboundId,
            actualQuantity: executeForm.actualQuantity, // 这里应该是实际输入的数量，不是计划数量
            inboundName: executeForm.inboundName,
            warehouseId: executeForm.warehouseId,
            planId:executeForm.planId,
            productId: executeForm.materialId,
            operatorId: executeForm.operatorId,
            batchNo: executeForm.batchNo
        }
        console.log('执行入库参数:', data)

        await request({
            url: '/inboundOrder/execute',
            method: 'post',
            data: data
        })
        
        ElMessage.success('入库执行成功')
        executeDialogVisible.value = false
        loadData() // 刷新表格数据
    
    } catch (error) {
        console.error('执行入库失败:', error)
        if (error && error !== 'cancel') {
            ElMessage.error('执行入库失败: ' + (error.message || '请检查网络连接'))
        }
    } finally {
        executing.value = false
    }
}

// 数量验证
const validateQuantity = (rule, value, callback) => {
    if (!value && value !== 0) {
        callback(new Error('请输入实际数量'))
    } else if (value < 0) {
        callback(new Error('数量不能小于0'))
    } else if (value > executeForm.totalQuantity) {
        callback(new Error(`实际数量不能超过计划数量 ${executeForm.totalQuantity}`))
    } else {
        callback()
    }
}

// 搜索
const handleSearch = () => {
    page.value.current = 1
    loadData()
}

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields()
    handleSearch()
}

// 分页大小改变
const handleSizeChange = (size) => {
    page.value.size = size
    page.value.current = 1
    loadData()
}

// 当前页改变
const handleCurrentChange = (current) => {
    page.value.current = current
    loadData()
}

// 查看详情
const openDetailDialog = (row) => {
    dialogTitle.value = "入库单信息"
    currentRow.value = row
    dialogVisible.value = true
    router.push("/production/inbound/list")
}

// 弹窗控制
const refTable = () => {
    dialogVisible.value = false
    loadData() // 刷新表格数据
}

// 处理行选中
const handleSelectionChange = (val) => {
    selectedRows.value = val
}

// 添加入库单
const toInsert = () => {
    dialogTitle.value = "添加入库单"
    currentRow.value = null
    dialogVisible.value = true
    router.push('/production/inbound/insert')
}

// 修改入库单
const handleUpdate = (row) => {
    if (!row) return
    if (row.inboundStatus === 1) {
        ElMessage.warning('已完成的入库单不能修改')
        return
    }
    dialogTitle.value = "修改入库单"
    currentRow.value = row
    dialogVisible.value = true
    router.push('/production/inbound/update')
}

// 删除单条数据
const handleDelete = async (row) => {
    if (row.inboundStatus === 1) {
        ElMessage.warning('已完成的入库单不能删除')
        return
    }

    try {
        await ElMessageBox.confirm(`确定要删除入库单【${row.inboundCode}】吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await request({
            url: `/inboundOrder/delete`,
            method: 'delete',
            params: { inboundId: row.inboundId }
        })

        ElMessage.success('删除成功')
        loadData() // 重新加载数据
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (!selectedRows.value.length) return

    // 检查是否有已完成的入库单
    const completedOrders = selectedRows.value.filter(item => item.inboundStatus === 1)
    if (completedOrders.length > 0) {
        ElMessage.warning('包含已完成的入库单，不能删除')
        return
    }

    try {
        const codes = selectedRows.value.map(item => item.inboundCode).join('、')
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条入库单吗?<br>${codes}`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
        })

        const ids = selectedRows.value.map(item => item.inboundId)
        await request({
            url: '/inboundOrder/batch',
            method: 'delete',
            data: ids
        })

        ElMessage.success('批量删除成功')
        selectedRows.value = []
        loadData() // 重新加载数据
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
        }
    }
}

// 处理弹窗关闭
const handleDialogClosed = () => {
    router.push('/production/inbound')
}

// 日期格式化
const formatDate = (date) => {
    if (!date) return ''
    return new Date(date).toLocaleDateString('zh-CN')
}

// 状态标签样式
const getStatusTagType = (inboundStatus) => {
    const map = {
        1: 'success',    // 已完成
        0: 'warning',    // 进行中
        2: 'danger'      // 已取消
    }
    return map[inboundStatus] || 'info'
}

// 状态文本
const getStatusText = (inboundStatus) => {
    const map = {
        0: '未开始',
        1: '已完成',
        2: '已取消'
    }
    return map[inboundStatus] || '未知'
}

// 组件挂载时加载数据
onMounted(() => {
    loadWarehouseList()
    loadData()
})
</script>

<style scoped>
.inbound-management-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
}

.header-title {
    font-size: 18px;
    font-weight: bold;
    color: var(--el-text-color-primary);
}

.search-operation-area {
    margin-bottom: 20px;
}

.search-form {
    margin-bottom: 15px;
}

.action-buttons {
    margin-bottom: 15px;
}

.pagination-container {
    margin-top: 20px;
    justify-content: flex-end;
}

.el-table {
    margin-top: 15px;
}

.el-tag {
    margin: 2px;
}
</style>